package com.example.androidframework.ui.course.dialog

import android.content.Context
import android.content.DialogInterface
import com.example.androidframework.R
import com.example.androidframework.databinding.DialogCommentInputBinding
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.util.KeyboardUtils
import com.martin.lib_base.base.BaseDialogModel
import com.martin.lib_base.bean.EmojiBean
import com.martin.lib_base.constant.ConstantKey
import com.martin.lib_base.interfaces.IOnItemClickListener
import com.martin.lib_base.ktx.addOnItemClickListener
import com.martin.lib_base.ktx.getActivity
import com.martin.lib_base.ktx.refresh
import com.tencent.mmkv.MMKV
import dev.utils.app.ViewUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

class CommentInputDialogView : BaseDialogModel<DialogCommentInputBinding>(), CoroutineScope by MainScope() {
    val emojiViewHolders = listOf(EmojiViewHolder::class.java)
    // 输入的内容
    val inputText = MutableStateFlow("")
    // 键盘是否弹出
    private var keyboardIsShow: Boolean = false

    override fun layoutId(): Int {
        return R.layout.dialog_comment_input
    }

    override fun onBuild(builder: XPopup.Builder) {
        super.onBuild(builder)
        // 设置View不自动上弹到键盘上方
        builder.moveUpToKeyboard(false).autoOpenSoftInput(true).autoFocusEditText(true)
    }

    override fun onDialogCreated(context: Context) {
        binding.apply {
            model = this@CommentInputDialogView

            // 表情点击事件
            rv.addOnItemClickListener(object : IOnItemClickListener {
                override fun onItemClick(position: Int, type: Int) {

                }
            })

            // 根据键盘高度设置rv的高度
            val keyboardHeight = MMKV.defaultMMKV().getInt(ConstantKey.KEYBOARD_HEIGHT, 0)
            if (keyboardHeight > 0) {
                ViewUtils.setHeight(rv, keyboardHeight)
            }

            // 监听键盘弹出
            root.context.getActivity()?.let {
                KeyboardUtils.registerSoftInputChangedListener(it.window, dialog) { height ->
                    rv.post {
                        keyboardIsShow = height > 0
                        if (keyboardIsShow && rv.height != height) {
                            ViewUtils.setHeight(rv, height)
                            MMKV.defaultMMKV().putInt(ConstantKey.KEYBOARD_HEIGHT, height)
                        }
                    }
                }
            }

            // 设置表情数据
            val emojiList = context.resources.getIntArray(R.array.emoji_code).toList().map {
                EmojiBean(it)
            }
            rv.refresh(emojiList)
        }

        // 启动协程
        launch {
            inputText.collect {

            }
        }
    }

    override fun onDismiss(d: DialogInterface?) {
        super.onDismiss(d)
        // 取消协程
        cancel()
    }
}